<template>
  <div class="expression-analysis">
    <!-- 实时分析状态 -->
    <div v-if="isAnalyzing" class="analysis-status">
      <el-alert
        title="正在分析面部表情"
        type="info"
        :closable="false"
        show-icon
      >
        <template #default>
          <div class="analysis-progress">
            <el-progress 
              :percentage="analysisProgress" 
              :stroke-width="6"
              :show-text="false"
            />
            <span class="progress-text">{{ analysisProgress }}% 完成</span>
          </div>
          <p>正在分析专注度、情绪、姿态和视线...</p>
        </template>
      </el-alert>
    </div>

    <!-- 分析结果展示 -->
    <div v-if="analysisResult && !isAnalyzing" class="analysis-results">
      <div class="results-header">
        <h4>面部表情分析结果</h4>
        <el-tag :type="getOverallEvaluationType(analysisResult.overall_evaluation)">
          {{ analysisResult.overall_evaluation }}
        </el-tag>
      </div>

      <!-- 综合评分 -->
      <div class="overall-score">
        <div class="score-circle">
          <div class="score-value">{{ analysisResult.expression_avg_score || 0 }}</div>
          <div class="score-label">综合得分</div>
        </div>
      </div>

      <!-- 详细评分 -->
      <div class="detailed-scores">
        <div class="score-item">
          <div class="score-label">专注度</div>
          <div class="score-value">{{ analysisResult.average_concentration || 0 }}</div>
          <el-progress 
            :percentage="analysisResult.average_concentration || 0" 
            :stroke-width="4"
            :show-text="false"
            :color="getScoreColor(analysisResult.average_concentration)"
          />
        </div>

        <div class="score-item">
          <div class="score-label">情绪表现</div>
          <div class="score-value">{{ analysisResult.emotion_avg_score || 0 }}</div>
          <el-progress 
            :percentage="analysisResult.emotion_avg_score || 0" 
            :stroke-width="4"
            :show-text="false"
            :color="getScoreColor(analysisResult.emotion_avg_score)"
          />
        </div>

        <div class="score-item">
          <div class="score-label">姿态控制</div>
          <div class="score-value">{{ analysisResult.pose_avg_score || 0 }}</div>
          <el-progress 
            :percentage="analysisResult.pose_avg_score || 0" 
            :stroke-width="4"
            :show-text="false"
            :color="getScoreColor(analysisResult.pose_avg_score)"
          />
        </div>

        <div class="score-item">
          <div class="score-label">视线管理</div>
          <div class="score-value">{{ analysisResult.gaze_avg_score || 0 }}</div>
          <el-progress 
            :percentage="analysisResult.gaze_avg_score || 0" 
            :stroke-width="4"
            :show-text="false"
            :color="getScoreColor(analysisResult.gaze_avg_score)"
          />
        </div>
      </div>

      <!-- 帧分析结果 -->
      <div v-if="analysisResult.frame_results && analysisResult.frame_results.length > 0" class="frame-analysis">
        <h5>详细帧分析</h5>
        <div class="frame-grid">
          <div 
            v-for="(frame, index) in analysisResult.frame_results.slice(0, 6)" 
            :key="index"
            class="frame-item"
          >
            <div class="frame-header">
              <span class="frame-time">{{ getFrameTime(frame.frame_name) }}</span>
              <el-tag size="small" :type="getEmotionType(frame.primary_emotion)">
                {{ getEmotionLabel(frame.primary_emotion) }}
              </el-tag>
            </div>
            <div class="frame-scores">
              <div class="mini-score">
                <span>专注: {{ frame.concentration_score }}</span>
                <el-progress 
                  :percentage="frame.concentration_score" 
                  :stroke-width="2"
                  :show-text="false"
                  :color="getScoreColor(frame.concentration_score)"
                />
              </div>
              <div class="mini-score">
                <span>情绪: {{ frame.emotion_score }}</span>
                <el-progress 
                  :percentage="frame.emotion_score" 
                  :stroke-width="2"
                  :show-text="false"
                  :color="getScoreColor(frame.emotion_score)"
                />
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 情绪分布 -->
      <div v-if="analysisResult.frame_results && analysisResult.frame_results.length > 0" class="emotion-distribution">
        <h5>情绪分布</h5>
        <div class="emotion-chart">
          <div 
            v-for="(emotion, key) in getEmotionDistribution()" 
            :key="key"
            class="emotion-bar"
          >
            <span class="emotion-label">{{ getEmotionLabel(key) }}</span>
            <div class="emotion-bar-container">
              <div 
                class="emotion-bar-fill"
                :style="{ width: emotion.percentage + '%' }"
                :class="getEmotionClass(key)"
              ></div>
            </div>
            <span class="emotion-value">{{ emotion.percentage }}%</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 分析失败提示 -->
    <div v-if="analysisError" class="analysis-error">
      <el-alert
        title="分析失败"
        type="error"
        :closable="false"
        show-icon
      >
        <template #default>
          <p>{{ analysisError }}</p>
          <el-button size="small" @click="retryAnalysis">重新分析</el-button>
        </template>
      </el-alert>
    </div>
  </div>
</template>

<script>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'ExpressionAnalysis',
  props: {
    videoFile: {
      type: File,
      default: null
    },
    analysisId: {
      type: [String, Number],
      default: null
    },
    autoAnalyze: {
      type: Boolean,
      default: true
    }
  },
  emits: ['analysis-complete', 'analysis-error'],
  setup(props, { emit }) {
    const isAnalyzing = ref(false)
    const analysisProgress = ref(0)
    const analysisResult = ref(null)
    const analysisError = ref(null)
    const analysisTimer = ref(null)

    // 监听视频文件变化，自动开始分析
    watch(() => props.videoFile, (newFile) => {
      if (newFile && props.autoAnalyze) {
        startAnalysis(newFile)
      }
    })

    // 监听分析ID变化，获取分析结果
    watch(() => props.analysisId, (newId) => {
      if (newId) {
        getAnalysisResult(newId)
      }
    })

    // 开始分析
    const startAnalysis = async (videoFile) => {
      if (!videoFile) return

      isAnalyzing.value = true
      analysisProgress.value = 0
      analysisError.value = null
      analysisResult.value = null

      try {
        // 模拟分析进度
        analysisTimer.value = setInterval(() => {
          if (analysisProgress.value < 90) {
            analysisProgress.value += Math.random() * 10
          }
        }, 500)

        // 这里应该调用实际的API
        // const response = await expressionApi.analyzeVideoAsync(videoFile)
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 3000))
        
        clearInterval(analysisTimer.value)
        analysisProgress.value = 100

        // 模拟分析结果
        const mockResult = {
          average_concentration: 75 + Math.random() * 20,
          emotion_avg_score: 70 + Math.random() * 25,
          pose_avg_score: 80 + Math.random() * 15,
          gaze_avg_score: 85 + Math.random() * 10,
          expression_avg_score: 77.5 + Math.random() * 15,
          overall_evaluation: '良好',
          frame_results: generateMockFrameResults()
        }

        analysisResult.value = mockResult
        emit('analysis-complete', mockResult)

      } catch (error) {
        console.error('分析失败:', error)
        analysisError.value = error.message || '分析失败，请重试'
        emit('analysis-error', error)
      } finally {
        isAnalyzing.value = false
        if (analysisTimer.value) {
          clearInterval(analysisTimer.value)
        }
      }
    }

    // 获取分析结果
    const getAnalysisResult = async (analysisId) => {
      try {
        // 这里应该调用实际的API
        // const response = await expressionApi.getAnalysisResult(analysisId)
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        const mockResult = {
          average_concentration: 75 + Math.random() * 20,
          emotion_avg_score: 70 + Math.random() * 25,
          pose_avg_score: 80 + Math.random() * 15,
          gaze_avg_score: 85 + Math.random() * 10,
          expression_avg_score: 77.5 + Math.random() * 15,
          overall_evaluation: '良好',
          frame_results: generateMockFrameResults()
        }

        analysisResult.value = mockResult
        emit('analysis-complete', mockResult)

      } catch (error) {
        console.error('获取分析结果失败:', error)
        analysisError.value = error.message || '获取分析结果失败'
        emit('analysis-error', error)
      }
    }

    // 重新分析
    const retryAnalysis = () => {
      if (props.videoFile) {
        startAnalysis(props.videoFile)
      }
    }

    // 生成模拟帧结果
    const generateMockFrameResults = () => {
      const emotions = ['neutral', 'happiness', 'surprise', 'sadness', 'anger', 'disgust', 'fear']
      const results = []
      
      for (let i = 0; i < 10; i++) {
        const emotion = emotions[Math.floor(Math.random() * emotions.length)]
        results.push({
          frame_name: `frame_${String(i + 1).padStart(4, '0')}_time_${(i + 1) * 5}.00s.jpg`,
          concentration_score: 60 + Math.random() * 40,
          primary_emotion: emotion,
          emotion_score: 65 + Math.random() * 30,
          pose_score: 70 + Math.random() * 25,
          gaze_score: 75 + Math.random() * 20,
          emotion_data: {
            happiness: Math.random(),
            surprise: Math.random(),
            neutral: Math.random(),
            sadness: Math.random(),
            anger: Math.random(),
            disgust: Math.random(),
            fear: Math.random()
          }
        })
      }
      
      return results
    }

    // 获取评分颜色
    const getScoreColor = (score) => {
      if (score >= 80) return '#67c23a'
      if (score >= 60) return '#e6a23c'
      return '#f56c6c'
    }

    // 获取整体评价类型
    const getOverallEvaluationType = (evaluation) => {
      switch (evaluation) {
        case '优秀': return 'success'
        case '良好': return 'warning'
        case '一般': return 'info'
        case '较差': return 'danger'
        default: return 'info'
      }
    }

    // 获取情绪类型
    const getEmotionType = (emotion) => {
      switch (emotion) {
        case 'happiness': return 'success'
        case 'neutral': return 'info'
        case 'surprise': return 'warning'
        case 'sadness': return ''
        case 'anger': return 'danger'
        case 'disgust': return 'danger'
        case 'fear': return 'danger'
        default: return 'info'
      }
    }

    // 获取情绪标签
    const getEmotionLabel = (emotion) => {
      const labels = {
        happiness: '开心',
        surprise: '惊讶',
        neutral: '平静',
        sadness: '悲伤',
        anger: '愤怒',
        disgust: '厌恶',
        fear: '恐惧'
      }
      return labels[emotion] || emotion
    }

    // 获取情绪样式类
    const getEmotionClass = (emotion) => {
      return `emotion-${emotion}`
    }

    // 获取帧时间
    const getFrameTime = (frameName) => {
      const match = frameName.match(/time_(\d+\.\d+)s/)
      if (match) {
        const seconds = parseFloat(match[1])
        const minutes = Math.floor(seconds / 60)
        const remainingSeconds = Math.floor(seconds % 60)
        return `${minutes}:${String(remainingSeconds).padStart(2, '0')}`
      }
      return '0:00'
    }

    // 获取情绪分布
    const getEmotionDistribution = () => {
      if (!analysisResult.value?.frame_results) return {}

      const emotions = ['happiness', 'surprise', 'neutral', 'sadness', 'anger', 'disgust', 'fear']
      const distribution = {}
      
      emotions.forEach(emotion => {
        distribution[emotion] = { count: 0, percentage: 0 }
      })

      analysisResult.value.frame_results.forEach(frame => {
        if (distribution[frame.primary_emotion]) {
          distribution[frame.primary_emotion].count++
        }
      })

      const total = analysisResult.value.frame_results.length
      emotions.forEach(emotion => {
        distribution[emotion].percentage = Math.round((distribution[emotion].count / total) * 100)
      })

      return distribution
    }

    return {
      isAnalyzing,
      analysisProgress,
      analysisResult,
      analysisError,
      startAnalysis,
      getAnalysisResult,
      retryAnalysis,
      getScoreColor,
      getOverallEvaluationType,
      getEmotionType,
      getEmotionLabel,
      getEmotionClass,
      getFrameTime,
      getEmotionDistribution
    }
  }
}
</script>

<style scoped>
.expression-analysis {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.analysis-status {
  margin-bottom: 20px;
}

.analysis-progress {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.progress-text {
  font-size: 14px;
  color: #666;
  min-width: 80px;
}

.analysis-results {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.results-header h4 {
  margin: 0;
  color: #333;
}

.overall-score {
  text-align: center;
  margin-bottom: 24px;
}

.score-circle {
  display: inline-block;
  width: 120px;
  height: 120px;
  border-radius: 50%;
  background: linear-gradient(135deg, #409eff, #67c23a);
  color: white;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.score-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 4px;
}

.score-label {
  font-size: 12px;
  opacity: 0.9;
}

.detailed-scores {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.score-item {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
}

.score-item .score-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.score-item .score-value {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.frame-analysis {
  margin-bottom: 24px;
}

.frame-analysis h5 {
  margin-bottom: 16px;
  color: #333;
}

.frame-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 12px;
}

.frame-item {
  background: #f8f9fa;
  padding: 12px;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.frame-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.frame-time {
  font-size: 12px;
  color: #666;
}

.frame-scores {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.mini-score {
  display: flex;
  align-items: center;
  gap: 8px;
}

.mini-score span {
  font-size: 11px;
  color: #666;
  min-width: 40px;
}

.emotion-distribution {
  margin-bottom: 20px;
}

.emotion-distribution h5 {
  margin-bottom: 16px;
  color: #333;
}

.emotion-chart {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.emotion-bar {
  display: flex;
  align-items: center;
  gap: 12px;
}

.emotion-label {
  font-size: 12px;
  color: #666;
  min-width: 40px;
}

.emotion-bar-container {
  flex: 1;
  height: 8px;
  background: #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
}

.emotion-bar-fill {
  height: 100%;
  transition: width 0.3s ease;
}

.emotion-value {
  font-size: 12px;
  color: #666;
  min-width: 30px;
  text-align: right;
}

/* 情绪颜色 */
.emotion-happiness {
  background: #67c23a;
}

.emotion-surprise {
  background: #e6a23c;
}

.emotion-neutral {
  background: #909399;
}

.emotion-sadness {
  background: #409eff;
}

.emotion-anger {
  background: #f56c6c;
}

.emotion-disgust {
  background: #8b4513;
}

.emotion-fear {
  background: #9932cc;
}

.analysis-error {
  margin-top: 20px;
}

.analysis-error .el-button {
  margin-top: 8px;
}
</style> 